﻿using System;
using System.Collections.Generic;
using System.Text;
using QD.Push.V3;
using QD.Push;
using WAD.DAL;
using System.Configuration;

namespace WAD.BLL
{
    public class PushBLL
    {
        private static object lockObj = new object();
        /// <summary>
        /// 批量推送通知
        /// </summary>
        /// <param name="article_id"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public static int Shared_Betch(int article_id, List<Dictionary<string, object>> list)
        {
            if (list == null)
            {
                DaoLogcat.Add("push", string.Format("开始推送：没有用户可以推,id:{0}", article_id));
                return 0;
            }

            int count = 0;
            string domain = System.Web.HttpContext.Current.Request.Url.Authority;
            List<object> listId = new List<object>();
            DaoLogcat.Add("push", string.Format("推送:{0}条,id:{1}", list.Count, article_id));

            lock (lockObj)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    string msg = string.Empty;
                    int clientid = Convert.ToInt32(list[i]["clientid"]);

                    if (clientid == Push_Client.ANDROID)    //安卓推送(批量)
                    {
                        listId.Add(list[i]["channelid"]);  //channelid列表
                        if (listId.Count > 500 || i == list.Count - 1)
                        {
                            System.Threading.Thread.Sleep(3000);    //降低推送频率
                            msg = AndroidBetch("抢红包啦", "有新的红包啦,马上开抢", listId, Push_Code.REDIRECT, string.Format("http://{0}/client/makesh_1.html?article_id={1}", domain, article_id));
                            listId.Clear();
                        }
                        count++;
                    }
                    else if (clientid == Push_Client.IOS)   //苹果推送
                    {
                        msg = IOS("抢红包啦", "有新的红包啦,马上开抢", Convert.ToString(list[i]["channelid"]), list[i]["store"], Push_Code.REDIRECT, string.Format("http://{0}/client/makesh_1.html?article_id={1}", domain, article_id));
                        //失败再推送一次
                        if (msg.IndexOf("success") == -1)
                        {
                            if (list[i]["store"].ToString().Equals("1"))
                                msg = IOS("抢红包啦", "有新的红包啦,马上开抢", Convert.ToString(list[i]["channelid"]), 0, Push_Code.REDIRECT, string.Format("http://{0}/client/makesh_1.html?article_id={1}", domain, article_id));
                            else
                                msg = IOS("抢红包啦", "有新的红包啦,马上开抢", Convert.ToString(list[i]["channelid"]), 1, Push_Code.REDIRECT, string.Format("http://{0}/client/makesh_1.html?article_id={1}", domain, article_id));
                        }
                        count++;
                    }

                    if (msg.IndexOf("fail") > -1)
                        DaoLogcat.Add("push", msg);
                }
            }

            if (list.Count > 0)
                DaoLogcat.Add("push", string.Format("结束推送,id:{0}", article_id));

            return count;
        }

        /// <summary>
        /// 推送安卓设备(通知)
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="description">描述</param>
        /// <param name="channelid">设备id</param>
        /// <param name="code">功能代码</param>
        /// <param name="data">传送数据</param>
        /// <returns></returns>
        public static string Android(string title, string description, string channelId, int code, object data)
        {
            QD.Push.V3.Push push = new QD.Push.V3.Push("POST", Push_Config.SecretKey);
            Notification_Android notification = new Notification_Android(title, description);
            notification.custom_content.code = code;
            notification.custom_content.data = data;
            String msg = notification.getJsonString();

            PushOptions pOpts = new PushOptions(Push_Config.ApiKey, channelId, msg, mDeviceType.Andriod);

            return push.PushMessage(pOpts);
        }

        /// <summary>
        /// 推送苹果设备
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="description">描述</param>
        /// <param name="channelid"></param>
        /// <param name="store">0 企业版, 1 appstore个人版</param>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string IOS(string title, string description, string channelId, object store, int code, object data)
        {
            Notification_IOS notification = new Notification_IOS(title, description);
            notification.code = code;
            notification.data = data;
            string messages = notification.getJsonString();

            if (store != null && store != DBNull.Value && store.ToString().Equals("1"))
            {
                PushOptions pOpts = new PushOptions(Push_Config.ApiKey_IOS_Store, channelId, messages, mDeviceType.IOS);
                pOpts.deploy_status = 2;
                Push push = new Push("POST", Push_Config.SecretKey_IOS_Store);
                return push.PushMessage(pOpts);
            }
            else
            {
                PushOptions pOpts = new PushOptions(Push_Config.ApiKey_IOS, channelId, messages, mDeviceType.IOS);
                pOpts.deploy_status = 2;
                Push push = new Push("POST", Push_Config.SecretKey_IOS);
                return push.PushMessage(pOpts);
            }
        }

        /// <summary>
        /// 批量单播(每批50个)
        /// </summary>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="list"></param>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string AndroidBetch(string title, string description, List<object> listId, int code, object data)
        {
            if (listId.Count < 1) return "";
            QD.Push.V3.Push push = new QD.Push.V3.Push("POST", Push_Config.SecretKey);
            Notification_Android notification = new Notification_Android(title, description);
            notification.custom_content.code = code;
            notification.custom_content.data = data;
            string msg = notification.getJsonString();

            PushOptions opts = new PushOptions(Push_Config.ApiKey, msg);
            opts.device_type = (uint)mDeviceType.Andriod;  //安卓设备
            opts.channel_ids = notification.getJsonString(listId);

            string s = push.PushMessageBetch(opts);
            listId.Clear();    //清空channel_id
            return s;
        }

        /// <summary>
        /// 内侧账号，发送抢红包通知，并自动更新定位
        /// </summary>
        /// <param name="article_id"></param>
        /// <param name="user_ids"></param>
        /// <param name="area1"></param>
        /// <param name="area2"></param>
        /// <param name="area3"></param>
        public static void PushOtherUser(int article_id, object area1, object area2, object area3)
        {
            string user_ids = ConfigurationManager.AppSettings["FC_Qiang_User_Id"];
            if (string.IsNullOrEmpty(user_ids))
                return;

            List<Dictionary<string, object>> list = DAOPush.GetList(string.Format("user_id in ({0})", user_ids), 100, "push");

            if (list.Count == 0)
                return;

            //选了省份的红包，则更新用户的定位
            if (area1 != null && area1 != DBNull.Value)
            {
                string[] ids = user_ids.Split(',');
                if (area2 == null || area2 == DBNull.Value) area2 = "";
                if (area3 == null || area3 == DBNull.Value) area3 = "";
                for (int i = 0; i < ids.Length; i++)
                {
                    DAOFCSetting.ExecuteNonQuery(string.Format("update fc_setting set area1='{0}',area2='{1}',area3='{2}' where user_id={3}", area1, area2, area3, ids[i]));
                }
            }

            //发推送
            for (int i = 0; i < list.Count; i++)
            {
                string msg = string.Empty;
                int clientid = Convert.ToInt32(list[i]["clientid"]);
                string domain = System.Web.HttpContext.Current.Request.Url.Authority;
                if (clientid == Push_Client.ANDROID)    //安卓推送(单播)
                {
                    msg = Android("抢红包啦", "内侧账号抢红包啦,马上开抢", Convert.ToString(list[i]["channelid"]), Push_Code.REDIRECT, string.Format("http://{0}/client/makesh_1.html?article_id={1}", domain, article_id));
                }
                else if (clientid == Push_Client.IOS)   //苹果推送
                {
                    msg = IOS("抢红包啦", "内侧账号抢红包啦,马上开抢", Convert.ToString(list[i]["channelid"]), list[i]["store"], Push_Code.REDIRECT, string.Format("http://{0}/client/makesh_1.html?article_id={1}", domain, article_id));
                }
            }
        }
    }

    public class Push_Config
    {
        public static string ApiKey = "my77cOj4TOR5ApsFwf7A4gGG";

        public static string SecretKey = "WGAS1qnsMG1GNQarBgH5kSsC5OHsHDu1";

        /// <summary>
        /// 企业版KEY
        /// </summary>
        public static string ApiKey_IOS = "IDO3XqDmFU668Zlu0xy7iQj5";
        /// <summary>
        /// 企业版KEY
        /// </summary>
        public static string SecretKey_IOS = "yojtplZvWnqup0qp1mpvuA4QG7DuuutB";

        /// <summary>
        /// appstore KEY
        /// </summary>
        public static string ApiKey_IOS_Store = "dQIWIyimLdTjXbPVANiMvGIR";
        /// <summary>
        /// Appstore
        /// </summary>
        public static string SecretKey_IOS_Store = "Ag8AaRAaiHkNj2PzsHFInvsBLcB5OfW0";
    }

    /// <summary>
    /// 推送到客户端要执行的功能代码
    /// </summary>
    public class Push_Code
    {

        /// <summary>
        /// 跳转到指定url
        /// </summary>
        public const int REDIRECT = 1;

        /// <summary>
        /// 软件更新推送
        /// </summary>
        public const int UPDATE = 2;
    }

    public class Push_Client
    {
        /// <summary>
        /// android设备
        /// </summary>
        public const int ANDROID = 1;

        /// <summary>
        /// IOS设备
        /// </summary>
        public const int IOS = 2;
    }
}
